package com.yangxk.kadmin.web.module.gen.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yangxk.kadmin.common.exception.BizException;
import com.yangxk.kadmin.common.exception.ParamException;
import com.yangxk.kadmin.common.util.ValidUtil;
import com.yangxk.kadmin.generator.constant.Vue;
import com.yangxk.kadmin.web.common.Const;
import com.yangxk.kadmin.web.common.enumeration.ResponseCode;
import com.yangxk.kadmin.web.module.gen.form.GenLogQueryForm;
import com.yangxk.kadmin.web.module.gen.mapper.GenLogFileMapper;
import com.yangxk.kadmin.web.module.gen.mapper.GenLogMapper;
import com.yangxk.kadmin.web.module.gen.mapper.GenLogTableMapper;
import com.yangxk.kadmin.web.module.gen.po.GenLog;
import com.yangxk.kadmin.web.module.gen.po.GenLogFile;
import com.yangxk.kadmin.web.module.gen.po.GenLogTable;
import com.yangxk.kadmin.web.module.gen.util.DbUtil;
import com.yangxk.kadmin.web.module.gen.vo.GenLogDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.sql.DataSource;
import java.io.*;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

/**
 * 生成日志
 *
 * @author yangxk
 * @date 2018/10/12 14:23
 */
@Service
public class GenLogService {
    @Autowired
    private GenLogMapper genLogMapper;
    @Autowired
    private GenLogFileMapper fileMapper;
    @Autowired
    private GenLogTableMapper tableMapper;
    @Autowired
    private DataSource dataSource;


    @Transactional
    public void addLog(GenLog genLog, List<GenLogFile> logFileList, List<GenLogTable> logTableList) {
        genLogMapper.insertSelective(genLog);
        fileMapper.insertBatch(logFileList);
        tableMapper.inserBatch(logTableList);
    }

    /**
     * 分页查询
     * create by yangxk on 2018/10/12 16:05
     */
    public PageInfo<GenLog> findByPage(GenLogQueryForm queryForm) {

        PageHelper.startPage(queryForm.getPageNum(), queryForm.getPageSize());
        List<GenLog> genLogs = genLogMapper.selectList(queryForm);
        PageInfo<GenLog> pageInfo = new PageInfo<>(genLogs);

        return pageInfo;
    }

    /**
     * 查询生成日志详情
     * create by yangxk on 2018/10/12 16:15
     */
    public GenLogDetail findDetail(long genLogId) {
        GenLog genLog = genLogMapper.selectByPrimaryKey(genLogId);
        if (genLog == null)
            throw new BizException(ResponseCode.SELECT_CHECK_NULL);

        List<GenLogFile> genLogFiles = fileMapper.findByLogId(genLogId);
        List<GenLogTable> genLogTables = tableMapper.findByLogId(genLogId);

        GenLogDetail result = new GenLogDetail();
        result.setGenLog(genLog);
        result.setGenLogFiles(genLogFiles);
        result.setGenLogTables(genLogTables);

        return result;
    }

    /**
     * 撤销生成操作
     * create by yangxk on 2018/10/13 9:11
     */
    @Transactional
    public void repealGen(long genLogId) {
        GenLogDetail detail = findDetail(genLogId);
        GenLog genLog = detail.getGenLog();
        if (genLog.getState().equals(Const.GEN_STATE.DEL))
            throw new BizException(ResponseCode.GEN_LOG_RESET_REPEAT);

        // 处理生成的文件及数据库
        handleFile(detail.getGenLogFiles());
        handleTable(detail.getGenLogTables());

        //  更新日志状态为已撤销
        genLog.setState(Const.GEN_STATE.DEL);
        genLogMapper.updateByPrimaryKeySelective(genLog);
    }

    private void handleTable(List<GenLogTable> genLogTables) {
        Connection connection = DbUtil.getConnection(dataSource);
        for (GenLogTable genLogTable : genLogTables) {
            DbUtil.deleteById(connection, genLogTable.getTableName(), genLogTable.getRecordId());
        }
        DbUtil.close(connection);
    }

    private void handleFile(List<GenLogFile> genLogFiles) {
        List<String> addFiles = new ArrayList<>();
        List<GenLogFile> updateFiles = new ArrayList<>();
        for (GenLogFile genLogFile : genLogFiles) {
            if (genLogFile.getType().equals(Const.GEN_TYPE.GEN)) {
                addFiles.add(genLogFile.getPath());
            } else {
                updateFiles.add(genLogFile);
            }
        }

        // 删除生成的文件
        deleteFile(addFiles);

        // 处理修改的文件
        handleUpdateFile(updateFiles);
    }

    private void handleUpdateFile(List<GenLogFile> updateFiles) {
        for (GenLogFile updateFile : updateFiles) {
            String content = updateFile.getContent();
            String[] lines = content.split("###");
            String path = updateFile.getPath();

            try{
                File target = new File(path);
                File tmp = new File(path + ".tmp");
                BufferedReader br = new BufferedReader(new FileReader(target));
                BufferedWriter bw = new BufferedWriter(new FileWriter(tmp));
                String str = "";
                int i = 0;
                int len = lines.length;
                while ((str = br.readLine()) != null) {
                    if (i < len && str.trim().equals(lines[i].trim())) {
                        i++;
                        continue;
                    }

                    bw.write(str);
                    bw.newLine();
                }

                bw.close();
                br.close();

                target.delete();
                tmp.renameTo(new File(path));
            }catch (Exception e) {

            }
        }
    }

    private void deleteFile(List<String> paths) {
        if (ValidUtil.isEmpty(paths))
            return ;

        for (String path : paths) {
            File file = new File(path);
            file.delete();
        }

    }
}
